import os
import re
import sys
from pathlib import Path

def fix_file(file_path):
    """修复文件中的字符串错误"""
    print(f"Processing file: {file_path}")
    
    # 尝试多种编码读取文件
    encodings = ['utf-8', 'gbk', 'gb2312', 'latin1', 'cp1252']
    content = None
    encoding_used = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            encoding_used = encoding
            print(f"  Successfully read with encoding: {encoding}")
            break
        except UnicodeDecodeError:
            continue
    
    if content is None:
        print(f"  Could not read file with any encoding")
        return False
    
    # 分割为行
    lines = content.split('\n')
    fixed_lines = []
    string_literal_stack = []
    
    i = 0
    while i < len(lines):
        line = lines[i]
        line_num = i + 1
        
        # 检查未结束的字符串文字
        if '"' in line:
            # 计算引号数量
            quote_count = line.count('"')
            
            # 如果引号数量是奇数，说明有未结束的字符串
            if quote_count % 2 == 1:
                print(f"    Line {line_num}: Unmatched quotes found, fixing...")
                # 添加一个引号来结束字符串
                line = line + '"'
        
        # 处理包含非UTF-8字符的行
        try:
            line.encode('utf-8')
            fixed_lines.append(line)
        except UnicodeEncodeError:
            # 如果不能编码为UTF-8，替换或删除该行
            # 尝试移除非UTF-8字符
            try:
                clean_line = ''.join(c for c in line if ord(c) < 128 or c in '\n\r\t')
                fixed_lines.append(clean_line)
                print(f"    Line {line_num}: Cleaned non-UTF-8 characters")
            except:
                print(f"    Line {line_num}: Skipping problematic line")
                # 可以选择添加一个空行或注释
                fixed_lines.append(f"// Line {line_num}: Original line contained invalid characters")
        
        i += 1
    
    # 写回文件
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(fixed_lines))
        print(f"  Successfully fixed file")
        return True
    except Exception as e:
        print(f"  Error writing file: {e}")
        return False

def main():
    # 从命令行参数获取文件路径，如果没有提供则使用默认路径
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
    else:
        file_path = "gate-server/src/main/java/com/lastwar/gateserver/login/LoginHandler.java"
    
    if not os.path.isabs(file_path):
        # 如果是相对路径，基于当前脚本目录
        script_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(script_dir, file_path)
    
    if os.path.isfile(file_path):
        fix_file(file_path)
    else:
        print(f"File not found: {file_path}")

if __name__ == "__main__":
    main()